package com.ruoyi.carton.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.carton.domain.Box;
import com.ruoyi.carton.domain.OrderOutbound;
import com.ruoyi.carton.domain.OrderStatus;
import com.ruoyi.carton.domain.Orders;
import com.ruoyi.carton.domain.bo.OrderOutboundBO;
import com.ruoyi.carton.domain.vo.OrderOutboundQuery;
import com.ruoyi.carton.domain.vo.OrderOutboundUpdateVO;
import com.ruoyi.carton.mapper.BoxMapper;
import com.ruoyi.carton.mapper.OrderOutboundMapper;
import com.ruoyi.carton.mapper.OrdersMapper;
import com.ruoyi.carton.service.BoxService;
import com.ruoyi.carton.service.OrderOutboundService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
* @author 时空
* @description 针对表【order_outbound(纸箱出库单)】的数据库操作Service实现
* @createDate 2025-07-01 17:42:41
*/
@Service
public class OrderOutboundServiceImpl extends ServiceImpl<OrderOutboundMapper, OrderOutbound>
    implements OrderOutboundService{
    @Autowired
    private BoxService boxService;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private BoxMapper boxMapper;
    @Autowired
    private OrderOutboundMapper orderOutboundMapper;

    @Override
    public void createOutboundReceipt(Orders order) {
        if (order == null || order.getId() == null) {
            throw new IllegalArgumentException("订单信息不能为空");
        }
        // 通过 productId 查询 Box 信息
        String boxId = order.getProductId();
        if (boxId == null) {
            throw new IllegalArgumentException("订单缺少产品编号（boxId）");
        }

        Box box = boxService.getById(boxId);
        if (box == null) {
            throw new IllegalArgumentException("未找到对应的纸箱信息");
        }

        OrderOutbound orderOutbound = new OrderOutbound();
        orderOutbound.setOrderId(order.getId());
        orderOutbound.setBoxId(order.getProductId());
        orderOutbound.setCustomerName(order.getCustomerName());
        orderOutbound.setOutboundDate(LocalDateTime.now());
        orderOutbound.setCreateTime(LocalDateTime.now());
        orderOutbound.setFluteType(box.getFluteType());
        this.save(orderOutbound);

    }

    @Override
    public OrderOutboundBO getOutboundById(Integer id) {
        OrderOutbound outbound = this.getById(id);
        if (outbound == null) {
            throw new ServiceException("出库单不存在");
        }

        OrderOutboundBO bo = new OrderOutboundBO();
        BeanUtils.copyProperties(outbound, bo);
//        // 1. 通过 OrderId 查询 Orders 表
//        Orders order = ordersMapper.selectById(outbound.getOrderId());
//        if (order != null) {
//            bo.setCustomerName(order.getCustomerName());
//            bo.setOrderId(order.getId());
//        }
        bo.setCustomerName(outbound.getCustomerName());
        bo.setOrderId(outbound.getOrderId());

        // 查询纸箱
        Box box = boxMapper.selectById(outbound.getBoxId());
        if (box != null) {
            bo.setProductName(box.getProductName());
            bo.setLength(box.getLength());
            bo.setWidth(box.getWidth());
            bo.setHeight(box.getHeight());
            bo.setSalePrice(box.getSalePrice());
            bo.setFluteType(box.getFluteType());
        }
        bo.setQuantity(outbound.getQuantity());

//        // 计算金额
//        if (bo.getQuantity() != null && bo.getSalePrice() != null) {
//            bo.setTotalAmount(bo.getSalePrice().multiply(new BigDecimal(bo.getQuantity())));
//        }

        return bo;
    }

    @Override
    public List<OrderOutboundBO> selectOutboundList(OrderOutboundQuery query) {
        return orderOutboundMapper.selectOutboundList(query);
    }

    @Override
    public void removeOutboundById(Integer id) {
        // 获取出库单
        OrderOutbound outbound = orderOutboundMapper.selectById(id);
        if (outbound == null) {
            throw new ServiceException("出库记录不存在");
        }
        // 获取对应订单
        Orders order = ordersMapper.selectById(outbound.getOrderId());
        if (order == null) {
            throw new ServiceException("关联订单不存在");
        }
        // 校验状态是否为 OUT_STOCK
        if (order.getStatus() != OrderStatus.OUT_STOCK) {
            throw new ServiceException("当前订单状态不是出库，无法删除");
        }
        // 删除出库记录
        int rows = orderOutboundMapper.deleteById(id);
        if (rows == 0) {
            throw new ServiceException("删除失败");
        }
        // 回退订单状态为 IN_STOCK
        order.setStatus(OrderStatus.IN_STOCK);
        ordersMapper.updateById(order);
    }

    @Override
    public void updateOutboundById(OrderOutboundUpdateVO vo) {
        if (vo.getId() == null) {
            throw new ServiceException("出库单ID不能为空");
        }
        OrderOutbound outbound = orderOutboundMapper.selectById(vo.getId());
        if (outbound == null) {
            throw new ServiceException("出库单不存在");
        }
        // 手动拷贝属性
        outbound.setCustomerName(vo.getCustomerName());
        outbound.setQuantity(vo.getQuantity());
        outbound.setFluteType(vo.getFluteType());
        outbound.setVehicleNumber(vo.getVehicleNumber());
        outbound.setSupplierName(vo.getSupplierName());
        outbound.setCreatedBy(vo.getCreatedBy());
        outbound.setInventoryStaff(vo.getInventoryStaff());


        // 3. 获取 box.salePrice（由 boxId 关联）
        if (outbound.getBoxId() != null) {
            Box box = boxMapper.selectById(outbound.getBoxId());
            if (box != null && box.getSalePrice() != null && vo.getQuantity() != null) {
                // 计算金额 = 单价 * 数量
                BigDecimal amount = box.getSalePrice().multiply(BigDecimal.valueOf(vo.getQuantity()));
                outbound.setTotalAmount(amount);
            } else {
                outbound.setTotalAmount(BigDecimal.ZERO); // 默认置 0 防止空指针
            }
        }

        // 执行更新
        int rows = orderOutboundMapper.updateById(outbound);
        if (rows == 0) {
            throw new ServiceException("更新出库单失败");
        }
    }
}




